import React, { useState, useEffect } from 'react';
import { Row, Col, Form, Radio, Select, message, Button } from 'antd';
import { connect } from 'react-redux';
import FormItem from '../../../../components/FormItem';
import { randomKey } from '../../../../utils/utils';
import WarningRule from './Components/WarningRule';
import ReceiveUser from '../../components/ReceiveUser';
import { IS_RECEIVE } from 'src/utils/constant';
import services from 'src/services/api';
import './index.less';

const layout = {
  labelCol: {
    span: 4,
  },
  wrapperCol: {
    span: 20,
  },
};

// 按照key值顺序，对象转字符串，解决因key值顺序不同导致无法判断对象相等的问题
function obj2Str(obj) {
  if (!obj) {
    return randomKey();
  }
  return Object.keys(obj)
    .sort()
    .reduce((o, k) => {
      return `${o}-${k}-${obj[k]}`;
    }, '');
}

function WarningSetting(props) {
  const { form, receive_frequency: props_receive_frequency } = props;
  const [detail, setDetail] = useState({});
  // const [receive, setReceive] = useState(IS_RECEIVE._FALSE);
  const [rules, setRules] = useState([]);

  const { users, is_receive, receive_frequency } = detail;

  const isReceive =
    (form.getFieldValue('is_receive') === undefined && IS_RECEIVE._TRUE) ||
    form.getFieldValue('is_receive') === IS_RECEIVE._TRUE;

  useEffect(() => {
    services.devOpt.warningMonitorSettingGet().then((res) => {
      if (Object.keys(res.data).length > 0) {
        setDetail(res.data);
        const { is_receive, rules_list } = res.data;
        form.setFieldsValue({ is_receive });
        // setReceive(res.data.is_receive);
        setRules(rules_list);
      }
    });
  }, []);

  function validateRules() {
    if (rules.length === 0) {
      throw '请设置条件规则';
    }
    const nums = rules.reduce((o, t) => {
      const key = obj2Str(t.condition) + t.cycle;
      // 周期和规则完全相同的判定为相同数据
      o[key] = o[key] ? o[key] + 1 : 1;
      return o;
    }, {});
    const repeat = Object.values(nums).some((n) => n > 1);
    if (repeat) {
      throw '不能添加重复规则';
    }

    rules.forEach((rule) => {
      const condition = rule.condition;
      if (!condition.left_var_type || !condition.left_var_value) {
        throw '请设置服务名称';
      }
      if (!rule.cycle) {
        throw '请选择监控周期';
      }
      if (!condition.operator || condition.right_var_value.toString().length === 0) {
        throw '请设置报警规则';
      }
    });
  }

  function handleSubmit() {
    form.validateFields((err, values) => {
      console.log(err, values);
      if (!err) {
        const params = {
          ...values,
          rules_list: rules,
        };
        try {
          const { users } = values;
          if (users) {
            if (users.some((item) => !item.phone && !item.wx_work && !item.email)) {
              return message.warning('请至少填写一种接收方式');
            }
            params['users'] = users.filter(Boolean).map((item) => {
              const { key, label } = item.user_id;
              item['name'] = Array.isArray(label) ? label[0] : label;
              item['user_id'] = key;
              return item;
            });
          }
          validateRules();
          if (values.receive_obj) {
            const receive_obj = (values.receive_obj && values.receive_obj.replace(/\n/g, ',').replace(/\s/g, '')) || '';
            params.receive_obj = receive_obj.length > 0 ? receive_obj.split(',') : [];
          }
          services.devOpt.warningMonitorSetting(params).then((res) => {
            if (res.code === 0) {
              message.success(res.msg);
              props.history.push('/monitor/devOps/warning');
            } else {
              message.error(res.msg);
            }
          });
        } catch (err) {
          message.warning(err);
          return;
        }
      }
    });
  }

  function changeRules(rules) {
    setRules(rules);
  }
  const getFormItems = () => {
    return [
      {
        label: {
          label: '添加报警接收人',
          ...layout,
        },
        name: 'is_receive',
        options: {
          initialValue: (is_receive === undefined && IS_RECEIVE._TRUE) || is_receive,
          rules: [{ required: true, message: '请选择' }],
        },
        component: (
          <Radio.Group>
            <Radio value={IS_RECEIVE._TRUE}>是</Radio>
            <Radio value={IS_RECEIVE._FALSE}>否</Radio>
          </Radio.Group>
        ),
      },
      isReceive && {
        label: {
          label: '接收频率',
          ...layout,
        },
        name: 'receive_frequency',
        options: {
          initialValue: receive_frequency || '1|m',
          rules: [{ required: true, message: '请选择' }],
        },
        component: (
          <Select style={{ width: '200px' }}>
            {props_receive_frequency.map((it) => {
              return (
                <Select.Option value={it.key} key={it.key}>
                  {it.value}
                </Select.Option>
              );
            })}
          </Select>
        ),
        // after: (
        //   <Question
        //     title={
        //       '灰度百分比设置，如填写1，所有请求都需要过风控引擎；如填写0.5，则请求中50%经过风控引擎，另50%请求直接通过。'
        //     }
        //   />
        // ),
      },
      // receive === IS_RECEIVE._TRUE && {
      //   label: {
      //     label: '接收人列表',
      //     className: 'tantuer-form-item3 tantuer-form-item-nowrap',
      //   },
      //   name: 'receive_obj',
      //   options: {
      //     initialValue: detail.receive_obj instanceof Array ? detail.receive_obj.join('\n') : '',
      //     rules: [
      //       { required: true, message: '请输入' },
      //       {
      //         validator: (rule, value, callback) => {
      //           if (value) {
      //             const val = value
      //               .replace(/\n/g, ',')
      //               .replace(/\s/g, '')
      //               .split(',');
      //             const isValMatchEmailReg = val.every((o) => emailReg.test(o));
      //             !isValMatchEmailReg ? callback('无效的邮箱地址') : callback();
      //           } else {
      //             callback();
      //           }
      //         },
      //       },
      //     ],
      //   },
      //   component: (
      //     <Input.TextArea
      //       placeholder='每行请输入一个邮箱地址,输入完成后回车换行，&#10;实例:&#10;ABC@qq.com&#10;BCD@gmail.com'
      //       style={{ width: '400px', height: '90px' }}
      //     />
      //   ),
      // },
    ].filter(Boolean);
  };
  return (
    <div className='tantuer-form warning-setting'>
      <Form autoComplete='off'>
        <div className='tantuer-field-area'>
          <Row type='flex'>
            {getFormItems().map((item) => {
              return (
                <Col span={24} key={item.name}>
                  <FormItem form={form} item={item} colNum={2} />
                </Col>
              );
            })}
          </Row>
          {isReceive && (
            <Row type='flex'>
              <Col className='ant-form-item-label' span={3}>
                <label className='ant-form-item-required'>接收人</label>
              </Col>
              <Col className='ant-form-item-control-wrapper' span={21}>
                <ReceiveUser {...props} value={users} />
              </Col>
            </Row>
          )}
          <WarningRule value={rules || []} onChange={changeRules} />
        </div>
        <Row type='flex' justify='start' align='middle' className='operate_button'>
          <Button type='primary' onClick={handleSubmit}>
            确定
          </Button>
        </Row>
      </Form>
    </div>
  );
}

function mapStateToProps(state) {
  return {
    receive_frequency: state.code.receive_frequency || [],
  };
}

export default connect(mapStateToProps)(Form.create()(WarningSetting));
